//
//  LLPhotoBrowserViewController.swift
//  WeiBoShiBing
//
//  Created by Bingo on 15/11/8.
//  Copyright © 2015年 Bingo. All rights reserved.
//

import UIKit
import SVProgressHUD


let LLPhotoBrowserMinimumLineSpacing:CGFloat = 10

class LLPhotoBrowserViewController: UIViewController {

    private let cellIdentifier = "cellIdentifier"
    
    private var photoModels: [LLPhotoBrowserModel]
    
//    private var urls:[NSURL]
    
    private var selectedIndex:Int
    
    init(models:[LLPhotoBrowserModel],selectedIndex:Int){
        
        self.photoModels = models
        self.selectedIndex = selectedIndex
        
        super.init(nibName:nil,bundle:nil)
    }
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        prepareUI()
        // Do any additional setup after loading the view.
        
        pageLabel.text = "\(selectedIndex + 1) / \(photoModels.count)"
        
        view.backgroundColor = UIColor.clearColor()
    }
    
    override func viewWillAppear(animated: Bool) {
        super.viewWillAppear(animated)
        //让cell点击了滚动到点击的对应的图片
        let indexPath = NSIndexPath(forItem: selectedIndex, inSection: 0)
        
        collectionView.selectItemAtIndexPath(indexPath, animated: false, scrollPosition: UICollectionViewScrollPosition.Left)
    }
    
    private func prepareCollectionView(){
        
        collectionView.registerClass(LLPhotoBrowserCell.self, forCellWithReuseIdentifier:cellIdentifier)
        
        layout.itemSize = view.bounds.size
        
        layout.scrollDirection = UICollectionViewScrollDirection.Horizontal
        layout.sectionInset = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: LLPhotoBrowserMinimumLineSpacing)
        
        layout.minimumLineSpacing = LLPhotoBrowserMinimumLineSpacing
        layout.minimumInteritemSpacing = LLPhotoBrowserMinimumLineSpacing
        
        collectionView.bounces = false
        
        collectionView.backgroundColor = UIColor.clearColor()
        
        collectionView.pagingEnabled = true
        
        collectionView.delegate = self
        collectionView.dataSource = self
        
    }
    func closeClick(){
        
        dismissViewControllerAnimated(true, completion: nil)
    }
    func saveClick(){
//        print("还没开放此功能")
        let indexPath = collectionView.indexPathsForVisibleItems().first!
        
        let cell = collectionView.cellForItemAtIndexPath(indexPath) as! LLPhotoBrowserCell
        
        if let image = cell.imageView.image{
        
            UIImageWriteToSavedPhotosAlbum(image, self, "image:didFinshSavingWithError:contextInfo:", nil)
        }
    
    }
    
    func image(image:UIImage,didFinshSavingWithError error:NSError?,contextInfo:AnyObject){
    
        if error != nil {
            SVProgressHUD.showErrorWithStatus("保存失败", maskType: SVProgressHUDMaskType.Black)
            return
        }
        SVProgressHUD.showSuccessWithStatus("保存成功", maskType: SVProgressHUDMaskType.Black)
    }
    
    private func prepareUI(){
        
        view.addSubview(bkgView)
        view.addSubview(collectionView)
        view.addSubview(pageLabel)
        view.addSubview(closeButton)
        view.addSubview(saveButton)
        
        
        
        closeButton.addTarget(self, action: "closeClick", forControlEvents: UIControlEvents.TouchUpInside)
        saveButton.addTarget(self, action: "saveClick", forControlEvents: UIControlEvents.TouchUpInside)
        
        collectionView.translatesAutoresizingMaskIntoConstraints = false
        
        pageLabel.translatesAutoresizingMaskIntoConstraints = false
        
        closeButton.translatesAutoresizingMaskIntoConstraints = false
        saveButton.translatesAutoresizingMaskIntoConstraints = false
        
        
        bkgView.frame = view.bounds
        
        let views = ["cv" : collectionView,"pl":pageLabel,"cb":closeButton,"sb":saveButton]
        
        collectionView.frame = CGRect(x: 0, y: 0, width: UIScreen.mainScreen().bounds.width + LLPhotoBrowserMinimumLineSpacing, height: UIScreen.mainScreen().bounds.height)
        
//    view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[cv]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: views))
//        
//    view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-0-[cv]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: views))
        
       view.addConstraint(NSLayoutConstraint(item: pageLabel, attribute: NSLayoutAttribute.CenterX, relatedBy: NSLayoutRelation.Equal, toItem: view, attribute: NSLayoutAttribute.CenterX, multiplier: 1, constant: 0))
        
       view.addConstraint(NSLayoutConstraint(item: pageLabel, attribute: NSLayoutAttribute.Top, relatedBy: NSLayoutRelation.Equal, toItem: view, attribute: NSLayoutAttribute.Top, multiplier: 1, constant: 20))
        
    view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:[cb(35)]-8-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: views))
        
    view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:[sb(35)]-8-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: views))
        
    view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-8-[cb(75)]-(>=0)-[sb(75)]-8-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: views))
        
        prepareCollectionView()
    }
    
    private var layout = UICollectionViewFlowLayout()
    lazy var collectionView : UICollectionView = UICollectionView(frame: CGRectZero, collectionViewLayout:self.layout)
    
    private lazy var closeButton = UIButton(bkgImageName: "health_button_orange_line", title: "关闭", titleColor: UIColor.whiteColor(), fontSzie: 15)
    private lazy var saveButton = UIButton(bkgImageName: "health_button_orange_line", title: "保存", titleColor: UIColor.whiteColor(), fontSzie: 15)
    
    
    private lazy var pageLabel = UILabel(fonsize: 12, textColoc: UIColor.whiteColor())
    
    private lazy var bkgView:UIView = {
    
        let view = UIView()
        
        view.backgroundColor = UIColor(white: 0, alpha: 1)
        
        return view
    }()
}

extension LLPhotoBrowserViewController:UICollectionViewDelegate,UICollectionViewDataSource{
    
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return photoModels.count
    }
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(cellIdentifier, forIndexPath: indexPath) as! LLPhotoBrowserCell
//        cell.backgroundColor = UIColor.randomColor()
        
        cell.backgroundColor = UIColor.clearColor()
        cell.photoModel = photoModels[indexPath.item]
//        print("---------========\(cell.url)")
        
        cell.cellDelegate = self
        return cell
    }
    
    func scrollViewDidEndDecelerating(scrollView: UIScrollView) {
        
        let indexPath = collectionView.indexPathsForVisibleItems().first!
        
        selectedIndex = indexPath.item
        
        pageLabel.text = "\(selectedIndex + 1) / \(photoModels.count)"
    }
    
}

extension LLPhotoBrowserViewController:LLPhotoBrowserCellDelegate{

    func cellDismiss() {
        
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    func viewForTransparent() -> UIView {
        
        return bkgView
    }
    
}



extension LLPhotoBrowserViewController:UIViewControllerTransitioningDelegate{

    func animationControllerForPresentedController(presented: UIViewController, presentingController presenting: UIViewController, sourceController source: UIViewController) -> UIViewControllerAnimatedTransitioning?{
        
        return LLPhotoBrowserModalAnimation()
    }
    
    
    func animationControllerForDismissedController(dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning?{
    
        return LLPhotoBrowserDismissAnimation()
    
    }
}

extension LLPhotoBrowserViewController{

    func modalTempImageView()->UIImageView{
        
        let thumbImageView = photoModels[selectedIndex].imageView!
        
        let tempImageView = UIImageView(image: thumbImageView.image)
        
        tempImageView.contentMode = thumbImageView.contentMode
        
        tempImageView.clipsToBounds = true
        
        let rect = thumbImageView.superview!.convertRect(thumbImageView.frame, toCoordinateSpace: view)
        
        tempImageView.frame = rect
        
        return tempImageView
    }
    
    
    func modalTargetFrame() -> CGRect?{
    
        let thumbImageView = photoModels[selectedIndex].imageView!
        
        if thumbImageView.image == nil{
            
            return nil
        }
        
        let  thumbImage = thumbImageView.image!
        
        var newSize = thumbImage.displaySize()
        
        var offestY:CGFloat = 0
        if newSize.height < UIScreen.mainScreen().bounds.height{
        
            offestY = (UIScreen.mainScreen().bounds.height - newSize.height) * 0.5
            
        }else{
            
            newSize.height = UIScreen.mainScreen().bounds.height
        }
        
        return CGRect(x: 0, y: offestY, width: newSize.width, height: newSize.height)
    }
    
    func dismissTempImageView() ->UIImageView?{
    
        let indexPath = collectionView.indexPathsForVisibleItems().first!
        
        let cell = collectionView.cellForItemAtIndexPath(indexPath) as! LLPhotoBrowserCell
        
        if cell.imageView.image == nil {
        
            return nil
        }
        let image = cell.imageView.image!
        
        let tempImageView = UIImageView(image: image)
        
        
        tempImageView.contentMode = UIViewContentMode.ScaleAspectFill
        tempImageView.clipsToBounds = true
        
        let rect = cell.imageView.superview!.convertRect(cell.imageView.frame, toCoordinateSpace: view)
        
        tempImageView.frame = rect
        
        return tempImageView
    }
    
    func dismissTargetFrame() ->CGRect{
    
        let model = photoModels[selectedIndex]
        
        let thumbImageView = model.imageView
        
        let rect = model.imageView!.superview!.convertRect(model.imageView!.frame, toCoordinateSpace: view)
        
        return rect
    }
    
}
